#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include "getdatabasesettings.h"
#include "loadphotoncount.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    DatabaseOpen=false;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_action_Open_hovered()
{
    ui->action_Open->setEnabled(!DatabaseOpen);
    ui->action_Close->setEnabled(DatabaseOpen);
}

void MainWindow::on_action_Close_hovered()
{
    ui->action_Open->setEnabled(!DatabaseOpen);
    ui->action_Close->setEnabled(DatabaseOpen);
}

void MainWindow::on_action_Open_triggered()
{
    if (DatabaseOpen)
        return;
    GetDatabaseSettings DS(this);
    int Res=DS.exec();
    switch(Res)
    {
    case QDialog::Accepted:
        break;
    case QDialog::Rejected:
        return;
    }
    Db=QSqlDatabase::addDatabase("QMYSQL");
    Db.setHostName(DS.getHost());
    Db.setDatabaseName(DS.getDatabase());
    Db.setUserName(DS.getUser());
    Db.setPassword(DS.getPassword());
    DatabaseOpen=Db.open();
    if (!DatabaseOpen)
    {
        QSqlError Error=Db.lastError();
        QMessageBox::critical(this,
                              tr("Database error"),
                              Error.databaseText());
    }
}


void MainWindow::on_action_Close_triggered()
{
    QSqlDatabase::removeDatabase("");
    DatabaseOpen=false;
}


void MainWindow::on_action_Exit_triggered()
{
    close();
}

void MainWindow::on_actionPhoton_count_hovered()
{
    ui->actionPhoton_count->setEnabled(DatabaseOpen);
}

void MainWindow::on_actionPhoton_count_triggered()
{
    LoadPhotonCount LP(NULL);
    LP.exec();
}
